package avicit.bdp.dcs.utils.api;

import avicit.platform6.core.exception.BusinessException;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class APITest {

    public static RestTemplate getRestTemplate(){
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(5000);
        requestFactory.setReadTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        messageConverters.add(new FormHttpMessageConverter());

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setSupportedMediaTypes(Arrays.asList(MediaType.ALL));
        messageConverters.add(converter);

        restTemplate.getMessageConverters().addAll(messageConverters);

        return restTemplate;
    }

    public static HttpEntity<Object> buildHttpEntity(){
        // 创建一个头部对象
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/json;charset=UTF-8"));

        List<MediaType> mediaTypeList = new ArrayList<>();
        mediaTypeList.add(MediaType.ALL);
        headers.setAccept(mediaTypeList);

        return new HttpEntity<Object>(null, headers);
    }

    public static void main(String[] args) throws Exception {
        RestTemplate restTemplate = getRestTemplate();
        String url = "http://219.141.240.104:9090/api/bdp/dms/service/api/air/hours?token=8a58a4aa80175cfa0180a75769eb2757";

        try{
            HttpEntity<Object> httpEntity = buildHttpEntity();
            ResponseEntity<JSONObject> result = restTemplate.exchange(url, HttpMethod.GET, httpEntity, JSONObject.class);

            JSONObject body = result.getBody();
            String statusCode = body.getString("retCode");

            System.out.println("statusCode = " + statusCode);
        }catch (Exception e){
            e.printStackTrace();
            String msg = String.format("调用API接口失败,%s", e.getMessage());
            throw new BusinessException(msg);
        }
    }

}
